WordPress 自动为文章标签添加内链

网站外部链接建设固然重要,但很多人都有个SEO误区,认为网站排名是有外链决定的。

其实这种认识是非常错误的,网站排名与诸多因素有关,其中关于超链的因素有两个,一个是外链,一个是内链。

每个链接均是一个投票,只是内链的投票权值比外链要稍低,但仍然是有价值的。

所以你有必要在做外链的同时重视内链的建设。Wordpress内链建设最好的办法就是把文章标签转换为内链,一个标签页相当于一个专题,所以标签页的排名也至关重要。

但是,如果你给每一篇文章都手工添加内链,那就非常麻烦了。为此你也许会用一些内链插件,但其实所有的内链插件的原理都是基本一样的,也可以免插件实现自动把文章标签变为内链,本文就介绍这个方法。

将以下代码插入主题functions.php文件即可实现自动将标签转化为内链:

  1. /* 自动为文章标签添加内链 */     
  2.     $match_num_from = 1;        //一篇文章中同一个标签少于几次不自动链接     
  3.     $match_num_to = 1;      //一篇文章中同一个标签最多自动链接几次     
  4.     function tag_sort($a$b){     
  5.         if ( $a->name == $b->name ) return 0;     
  6.         return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;     
  7.     }     
  8.     function tag_link($content){     
  9.         global $match_num_from,$match_num_to;     
  10.             $posttags = get_the_tags();     
  11.             if ($posttags) {     
  12.                 usort($posttags"tag_sort");     
  13.                 foreach($posttags as $tag) {     
  14.                     $link = get_tag_link($tag->term_id);     
  15.                     $keyword = $tag->name;     
  16.                     $cleankeyword = stripslashes($keyword);     
  17.                     $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s'))."\"";     
  18.                     $url .= ' target="_blank"';     
  19.                     $url .= ">".addcslashes($cleankeyword, '$')."</a>";     
  20.                     $limit = rand($match_num_from,$match_num_to);     
  21.                     $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);     
  22.                     $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);     
  23.                     $cleankeyword = preg_quote($cleankeyword,'\'');     
  24.                     $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;     
  25.                     $content = preg_replace($regEx,$url,$content,$limit);     
  26.                     $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);     
  27.                 }     
  28.             }     
  29.         return $content;     
  30.     }     
  31.     add_filter('the_content','tag_link',1);